<?php
/**
 * @file : calendar.php
 * @date : 2014-12-26
 * @author : yuebin
 */
namespace haibao\cms\data;

use haibao\cms\model\filter\Calendar as CalendarFilter;

class Calendar extends \haibao\cms\data\BaseMysql{

    public function __construct(){
        parent::__construct('\haibao\cms\model\data\Calendar');
    }

    private static $collocation = 1;
    
    /**
     * 添加日历
     * @param Object \haibao\cms\model\data\Calendar $calendarModel
     */
    public function addCalendar($calendarModel){

        $this->beginTranscation();
        try{
        
           $this->add($calendarModel);
        
        } catch(\Exception $e){
        
        	$this->rollback();
        	throw $e;
        
        }
        $this->endTranscation();
        // 老表添加明星
        if(\haibao\classlibrary\cms\Config::getConfig(\haibao\classlibrary\cms\Config::SYNC_OLD)){
        	
        	$this->addOldCalendar($calendarModel);
    	}
    	return $calendarModel;
    }
    
  
    /**
     * 修改日历
     * @param Object \haibao\cms\model\data\Calendar $calendarModel
     */
    public function updateCalendar($calendarModel){
        $this->begintranscation();
        try{
        	
        	$this->updateById($calendarModel->Id,
        		array(
        			CalendarFilter::CONDITION_FIELD_NAME_TITLE => $calendarModel->Title,
        			CalendarFilter::CONDITION_FIELD_NAME_HOTIMAGEID => $calendarModel->HotImageId,
        		)
        	);
        	$this->updateOtherData($calendarModel);
	
        } catch (\Exception $e){
            $this->rollback();
        }
        $this->endtranscation();
        
        // 老表修改明星
        if(\haibao\classlibrary\cms\Config::getConfig(\haibao\classlibrary\cms\Config::SYNC_OLD)){
           $this->updateOldCalendar($calendarModel);
    	}
    }
    
    /**
     * 更新造型日历关联数据
     * @param Object \haibao\cms\model\data\Calendar $calendarModel
     */
    private function updateOtherData($calendarModel){
    	
    	$sql = "delete from CalendarPicPoint where CalendarId = %s";
    	$this->query($sql,array($calendarModel->Id));

    	$sql = "delete from CalendarProduct where CalendarId = %s";
    	$this->query($sql,array($calendarModel->Id));

    	$sql = "delete from CalendarRelAttr where CalendarId = %s";
    	$this->query($sql,array($calendarModel->Id));
    	
    	if($calendarModel->CalendarPicPoint){
    		
    		foreach($calendarModel->CalendarPicPoint as $picPoint){
    			$picPoint->CalendarId = $calendarModel->Id;
    		}
    		$this->addAll($calendarModel->CalendarPicPoint);
    	}
    	if($calendarModel->CalendarProduct){
    		foreach($calendarModel->CalendarProduct as $product){
    			$product->CalendarId = $calendarModel->Id;
    		}
    		$this->addAll($calendarModel->CalendarProduct);
    	}
    	if($calendarModel->CalendarRelAttr){
    		foreach($calendarModel->CalendarRelAttr as $relAttr){
    			$relAttr->CalendarId = $calendarModel->Id;
    		}
    		$this->addAll($calendarModel->CalendarRelAttr);
    	}
    }
    
    /**
     * 
     */
    public function getCalendarAttr($parentId){
    	if(empty($parentId)) return "";
		$CalendarAttr=array();
		$i = 0;
    	$sql="select Id,Name,ParentId from CalendarAttr where parentId = %s and Status = 1";
		$result = $this->query ( $sql ,array($parentId));
		while($result->fetch_assoc()){
			$CalendarAttr[$i]['id'] = $result->getData('Id');
			$CalendarAttr[$i]['name'] = $result->getData('Name');
			$CalendarAttr[$i]['parentId'] = $result->getData('ParentId');
			$i++;
		}
		
		return $CalendarAttr;
    }
    
    public function getCalendarId($articleId){
    	if(empty($articleId)) return "";
    	$CalendarId = "";
    	$sql="select Id from CalendarIndex where ArticleId = ".$articleId." and Status = 1";
    	$result = $this->query ( $sql );
    	while($result->fetch_assoc()){
    		$CalendarId = $result->getData('Id');    		
    	}
    	return $CalendarId;
    }
    
    public function getImageUrl($imageId){
    	if(empty($imageId)) return "";
    	$imageUrl = "";
    	$sql="select PicUrl from ArticleImage where  ImageId= ".$imageId." ";
    	$result = $this->query ( $sql );
    	while($result->fetch_assoc()){
    		$imageUrl = $result->getData('PicUrl');
    	}
    	return $imageUrl;    	
    }
    
    /**
     * 根据类别名称获取一条数据
     */
    public function getCalendarAttByName($name,$parentId){
    	return $this->query("select Name from CalendarAttr where Name = %s and Status = %s and ParentId = %s limit 1", array($name,\haibao\cms\model\data\CalendarAttr::STATUS_DELETE,$parentId))->fetch_assoc();

    }
    
    public function getCalendarAttByEditName($name,$id,$parentId){
    	return $this->query("select Name from CalendarAttr where Name = %s and Id<>%s and Status = %s and ParentId = %s limit 1", array($name,$id,\haibao\cms\model\data\CalendarAttr::STATUS_DELETE,$parentId))->fetch_assoc();
    
    }
    
    public function getOneCalendarAttr($id){
    	return $this->query("select Id,Name,ParentId from CalendarAttr where id = %s and Status = %s limit 1", array($id,\haibao\cms\model\data\CalendarAttr::STATUS_DELETE))->fetch_assoc();
    
    }
    
    /**
     * 添加造型日历分类
     */
    public function addCalendarAtt($model){
		$this->add($model);
		$nameResult = $this->query('select Name from CalendarAttr where Id = %s',array($model->Id))->fetch_assoc();
		$data = array(
			'Name'=>$nameResult['Name'],
			'Id'=>$model->Id
		);
		return $data;
    }
    
    /**
     * 删除造型日历分类
     */
    public function delCalendarAtt($id,$status = \haibao\cms\model\data\CalendarAttr::STATUS_ENABLE){
    	if(!$id) return false;
    	$this->query('update CalendarAttr set Status=%s where Id=%s limit 1', array(
		    $status, $id
		));
    }
    
    /**
     * 修改造型日历分类
     */
    public function updateCalendarAtt($model){
    	$this->query('update CalendarAttr set Name = %s where Id=%s limit 1', array(
    			$model->Name, $model->Id
    	));
    	
    }
    
    /***************同步老数据*****************/
    public function addOldCalendar($calendarModel){

    	$sql = "select OldPrimaryKey from DataMigrationMap where TableName = %s and PrimaryKey = %s";
    	$result = $this->query($sql,array('Article',$calendarModel->ArticleId))->fetch_assoc();
    	if($result){

    		$documentId = $result['OldPrimaryKey'];
    		
    		$productIds = '';
    		if($calendarModel->CalendarProduct){
    			$prodcutIdArr = array();
    			foreach($calendarModel->CalendarProduct as $prodcut){
    				array_push($prodcutIdArr, $prodcut->ProductId);
    			}
    			$productIds = implode(',',$prodcutIdArr).',';
    		}
    		
    		// DOTO : 处理hot_image_id
//     		$sql = "select ImageId from ArticleImage where ImageId=%s";
//     		$articleImageResult = $this->query($sql,array($calendarModel->HotImageId))->fetch_assoc();

    		$sql = "select OldPrimaryKey from DataMigrationMap where TableName = %s and PrimaryKey = %s";
    		$oldImageResult = $this->query($sql,array('ImageLibrary',$calendarModel->HotImageId))->fetch_assoc();
    		
    		$oldImageId = 0;
    		if($oldImageResult){
    			$oldImageId = $oldImageResult['OldPrimaryKey'];
    		}

    		$this->setConfig( \haibao\classlibrary\cms\Config::CLASSLIBRARY_CONFIG_MYSQL_HAIBAO_ARTICLE );
    		$hotImageId = 0;
    		if($oldImageId){
// 	    		$sql = "select pic_id from content_photo where article_id=%s and pic_id=%s and disrel=0 limit 1";
// 	    		$contentPhotoResult = $this->query($sql,array($documentId,$oldImageId));
// 	    		while($contentPhotoResult->fetch_assoc()){
// 	    			$hotImageId = $contentPhotoResult->getData('pic_id');
// 	    		}
    		}
    		// 同步主数据
    		$valArr = array();
    		$sql = "insert into `calendar_index` (document_id,product_id,gist,hot_photo_id,status,username,date) values (%s,%s,%s,%s,%s,%s,%s)";
    		array_push($valArr,$documentId);
    		array_push($valArr,$productIds);
    		array_push($valArr,$calendarModel->Title);
    		array_push($valArr,$oldImageId);
    		if($calendarModel->Status){
    			array_push($valArr,0);
    		}else{
    			array_push($valArr,1);
    		}
    		array_push($valArr,$calendarModel->CreateName);
    		array_push($valArr,$calendarModel->CreateTime);
    		$this->query($sql,$valArr);
    		
    		// 同步calendar_pic_point
    		if($calendarModel->CalendarPicPoint){

    			$sqlArr = $valArr = array();
    			$sql = "insert into `calendar_pic_point` (document_id,product_id,width,height,top_pos,`left`,label,url,username,`date`) values";
    			foreach($calendarModel->CalendarPicPoint as $picPoint){
    				array_push($sqlArr, '(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)');
    				array_push($valArr,$documentId);
    				array_push($valArr,12342234);
    				array_push($valArr,$picPoint->Width);
    				array_push($valArr,$picPoint->Height);
    				array_push($valArr,$picPoint->TopPos);
    				array_push($valArr,$picPoint->Left);
    				array_push($valArr,$picPoint->Title);
    				array_push($valArr,$picPoint->Url);
    				array_push($valArr,$calendarModel->CreateName);
    				array_push($valArr,$calendarModel->CreateTime);
    			}
    			
    			$sql .= implode(',',$sqlArr);
    			$this->query($sql,$valArr);
    		}
    		
    		// 同步calendar_rel_attr
    		if($calendarModel->CalendarRelAttr){
    			
    			$sqlArr = $valArr = array();
    			$sql = "insert into `calendar_rel_attr` (document_id,attrid,username,`date`) values";
    			foreach($calendarModel->CalendarRelAttr as $relAttr){
    				array_push($sqlArr, '(%s,%s,%s,%s)');
    				array_push($valArr,$documentId);
    				array_push($valArr,$relAttr->CalendarAttrId);
    				array_push($valArr,$calendarModel->CreateName);
    				array_push($valArr,$calendarModel->CreateTime);
    			}
    			$sql .= implode(',',$sqlArr);
    			$this->query($sql,$valArr);
    		}
    		
    		// 添加造型日历标签
    		$sql = "select count(*) as num from `rel_doc_tag` where `document_id`=".$documentId." and tag_id = 8411";
    		$count = $this->query($sql)->fetch_assoc();
    		if($count['num'] == 0) {
    			$sql = "insert into rel_doc_tag (document_id,tag_id,istpl,suser,lastmodified) values ($documentId,8411,0,'','".time()."')";
    			$this->query($sql);
    		}
    	}
    }
    
    public function updateOldCalendar($calendarModel){
    	 
    	$sql = "select OldPrimaryKey from DataMigrationMap where TableName = %s and PrimaryKey = %s";
    	$result = $this->query($sql,array('Article',$calendarModel->ArticleId))->fetch_assoc();
    	if($result){
    		
    		$documentId = $result['OldPrimaryKey'];
    		
    		$productIds = '';
    		if($calendarModel->CalendarProduct){
    			$prodcutIdArr = array();
    			foreach($calendarModel->CalendarProduct as $prodcut){
    				array_push($prodcutIdArr, $prodcut->ProductId);
    			}
    			$productIds = implode(',',$prodcutIdArr).',';
    		}
    		
    		// DOTO : 处理hot_image_id
//     		$sql = "select ImageId from ArticleImage where Id=%s";
//     		$articleImageResult = $this->query($sql,array($calendarModel->HotImageId))->fetch_assoc();

    		$sql = "select OldPrimaryKey from DataMigrationMap where TableName = %s and PrimaryKey = %s";
    		$oldImageResult = $this->query($sql,array('ImageLibrary',$calendarModel->HotImageId))->fetch_assoc();
    		
    		$oldImageId = 0;
    		if($oldImageResult){
    			$oldImageId = $oldImageResult['OldPrimaryKey'];
    		}

    		$this->setConfig( \haibao\classlibrary\cms\Config::CLASSLIBRARY_CONFIG_MYSQL_HAIBAO_ARTICLE );
    		$hotImageId = 0;
    		if($oldImageId){
// 	    		$sql = "select pic_id from content_photo where article_id=%s and pic_id=%s and disrel=0 limit 1";
// 	    		$contentPhotoResult = $this->query($sql,array($documentId,$oldImageId));
// 	    		while($contentPhotoResult->fetch_assoc()){
// 	    			$hotImageId = $contentPhotoResult->getData('pic_id');
// 	    		}
    		}
    		$this->setConfig( \haibao\classlibrary\cms\Config::CLASSLIBRARY_CONFIG_MYSQL_HAIBAO_ARTICLE );
    		
    		$sql = "update calendar_index set product_id=%s,gist=%s,hot_photo_id=%s,status=%s where document_id = %s";
    		if($calendarModel->Status){
    			$status = 0;
    		}else{
    			$status = 1;
    		}
    		$this->query($sql,array($productIds,$calendarModel->Title,$oldImageId,$status,$documentId));
    		
    		// 同步calendar_pic_point
    		$sql = "delete from calendar_pic_point where document_id = %s";
    		$this->query($sql,array($documentId));
    		
    		if($calendarModel->CalendarPicPoint){
    			$sqlArr = $valArr = array();
    			$sql = "insert into `calendar_pic_point` (document_id,product_id,width,height,top_pos,`left`,label,url,username,`date`) values";
    			foreach($calendarModel->CalendarPicPoint as $picPoint){
    				array_push($sqlArr, '(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)');
    				array_push($valArr,$documentId);
    				array_push($valArr,12342234);
    				array_push($valArr,$picPoint->Width);
    				array_push($valArr,$picPoint->Height);
    				array_push($valArr,$picPoint->TopPos);
    				array_push($valArr,$picPoint->Left);
    				array_push($valArr,$picPoint->Title);
    				array_push($valArr,$picPoint->Url);
    				array_push($valArr,$calendarModel->CreateName);
    				array_push($valArr,$calendarModel->CreateTime);
    			}
    			 
    			$sql .= implode(',',$sqlArr);
    			$this->query($sql,$valArr);
    		}
    		
    		// 同步calendar_rel_attr
    		$sql = "delete from calendar_rel_attr where document_id = %s";
    		$this->query($sql,array($documentId));
    		
    		if($calendarModel->CalendarRelAttr){
    			 
    			$sqlArr = $valArr = array();
    			$sql = "insert into `calendar_rel_attr` (document_id,attrid,username,`date`) values";
    			foreach($calendarModel->CalendarRelAttr as $relAttr){
    				array_push($sqlArr, '(%s,%s,%s,%s)');
    				array_push($valArr,$documentId);
    				array_push($valArr,$relAttr->CalendarAttrId);
					array_push($valArr,$calendarModel->CreateName);
    				array_push($valArr,$calendarModel->CreateTime);
    			}
    			$sql .= implode(',',$sqlArr);
    			$this->query($sql,$valArr);
    		}
    	}
    }

	public function getCalendarIndex(){
		$res = array();
		$sql = 'SELECT
			 a.Id as ArticleId,
			 a.ShortTitle,
			 a.Summary,
			 a.PublishId,
			 a.PublishTime,
				b.Title,
				b.HotImageId,
				b.Id as CalendarId
			FROM
			 Article AS a
			 INNER JOIN CalendarIndex AS b ON a.Id = b.ArticleId
			   WHERE
			 a.STATUS = '.\haibao\cms\model\data\Article::STATUS_ENABLE.'
			AND a.Published = '.\haibao\cms\model\data\Article::PUBLISHED_YES.'
			ORDER BY
			 a.PublishTime DESC
			LIMIT 5';

		$result = $this->query($sql);
		while($result->fetch_assoc()){
			$tag = $result->getData('CalendarId');
			$res[$tag]['Title'] = $result->getData('Title');
			$res[$tag]['CalendarId'] = $result->getData('CalendarId');
			$res[$tag]['ArticleId'] = $result->getData('ArticleId');
			$res[$tag]['ShortTitle'] = $result->getData('ShortTitle');
			$res[$tag]['HotImageId'] = $result->getData('HotImageId');
			$res[$tag]['Summary'] = $result->getData('Summary');
			$res[$tag]['PublishTime'] = $result->getData('PublishTime');
			$res[$tag]['PublishId'] = $result->getData('PublishId');
		}
		return $res;
	}

	public function getCalendarProduct($calendarIds){
		$products = $resArr = array();
		$str = implode(',',$calendarIds);
		$str = preg_replace('/(\d+)/','%s',$str);
		$sql = 'SELECT * FROM CalendarPicPoint WHERE CalendarId in ('.$str.')';
		$result = $this->query($sql,$calendarIds);
		if($result){
			$tag = 0;
			while($result->fetch_assoc()){
				$products[$tag]['Height'] = $result->getData('Height');
				$products[$tag]['Width'] = $result->getData('Width');
				$products[$tag]['TopPos'] = $result->getData('TopPos');
				$products[$tag]['Left'] = $result->getData('Left');
				$products[$tag]['Title'] = $result->getData('Title');
				$products[$tag]['Url'] = $result->getData('Url');
				$products[$tag]['CalendarId'] = $result->getData('CalendarId');
				$tag++;
			}
			foreach($products as $pro){
				$resArr[$pro['CalendarId']][] = $pro;
			}
		}
		return $resArr;

	}

	public function getRecommendProductsByCalendarId($calendarId){
		$categoryIds  = $modelIds = $resProduct = array();
		$sql = 'select p.CategoryId,pp.ProductId,pp.Id from Product p inner join (
					select pm.ProductId,pm.Id FROM ProductModel as pm
						INNER JOIN (
							select ProductId from CalendarProduct where CalendarId = %s
						) as cp ON pm.PublishId = cp.ProductId where pm.Status=%s
                    ) as pp on p.Id=pp.ProductId WHERE p.Status=%s';
		$result = $this->query($sql,array($calendarId,
					\haibao\cms\model\data\ProductModel::STATUS_ENABLE,
					\haibao\cms\model\data\Product::STATUS_ENABLE
		));
		if($result){
			while($result->fetch_assoc()){
				$categoryIds[] = $result->getData('CategoryId');
				$modelIds[] = $result->getData('Id');
			}
			$categoryIds = array_unique($categoryIds);
			if(!empty($categoryIds)){
				$onProduct = 0;
				foreach($categoryIds as $categoryId){
					$str = implode(',',$modelIds);
					$str = preg_replace('/(\d+)/','%s',$str);
					$sql = 'select pm.ProductName,pm.Id,pm.PicId,pm.PublishId,pm.ProductId
					from Product p LEFT JOIN ProductModel pm
						ON p.Id = pm.ProductId
						  WHERE p.CategoryId = '.$categoryId.' and
						   pm.Id not in('.$str.') and
						   pm.Status=1
					ORDER BY p.CreateTime DESC limit 1 ';

					$getProduct = $this->query($sql,$modelIds);
					if($getProduct){
						while($getProduct->fetch_assoc()){
							$modelIds[] = $getProduct->getData('Id');
							$resProduct[$onProduct]['Name'] = $getProduct->getData('ProductName');
							$resProduct[$onProduct]['PublishId'] = $getProduct->getData('PublishId');
							$resProduct[$onProduct]['PicId'] = $getProduct->getData('PicId');
							$resProduct[$onProduct]['ProductId'] = $getProduct->getData('ProductId');
						}
						$onProduct++;
					}
				}
				if($onProduct < 6){
					$limit = 6-$onProduct;
					$categoryStr = implode(',',$categoryIds);
					$categoryStr = preg_replace('/(\d+)/','%s',$categoryStr);
					$modelStr = implode(',',$modelIds);
					$modelStr = preg_replace('/(\d+)/','%s',$modelStr);
					$whereStr = $categoryIds ? 'p.CategoryId in ('.$categoryStr.') ' : '1';
					$sql = 'select pm.ProductName,pm.PicId,pm.PublishId,pm.ProductId
					from Product p LEFT JOIN ProductModel pm
						ON p.Id = pm.ProductId
						  WHERE '.$whereStr.' and
						   pm.Id not in('.$modelStr.') and
						   pm.Status=1
					ORDER BY p.CreateTime DESC limit '.$limit;
					$leftProduct = $this->query($sql,array_merge_recursive($categoryIds,$modelIds));
					if($leftProduct){
						while($leftProduct->fetch_assoc()){
							$onProduct++;
							$resProduct[$onProduct]['Name'] = $leftProduct->getData('ProductName');
							$resProduct[$onProduct]['PublishId'] = $leftProduct->getData('PublishId');
							$resProduct[$onProduct]['PicId'] = $leftProduct->getData('PicId');
							$resProduct[$onProduct]['ProductId'] = $leftProduct->getData('ProductId');
						}
					}
				}
			}

		}
		return $resProduct;

	}

	public function getProductsForCalendarArticle($calendarId){
		$sql = "select PM.Id,PM.ProductId,PM.ProductName,PM.PicId,PM.PublishId
						from CalendarProduct CP LEFT JOIN ProductModel PM
						on CP.ProductId = PM.PublishId
						WHERE CP.CalendarId = %s AND PM.Status = %s";
		$result = $this->query($sql,array($calendarId,\haibao\cms\model\data\ProductModel::STATUS_ENABLE));
		$productArr = array();
		if($result){
			while($result->fetch_assoc()){
				$productArr[$result->getData('Id')]['PublishId'] = $result->getData('PublishId');
				$productArr[$result->getData('Id')]['ProductName'] = $result->getData('ProductName');
				$productArr[$result->getData('Id')]['PicId'] = $result->getData('PicId');
				$productArr[$result->getData('Id')]['ProductId'] = $result->getData('ProductId');
			}
		}
		return $productArr;
	}

	public function getAllCalendarAttr(){
		$attrArr = $resArr = array();
		$sql = 'select Id,ParentId,Name from CalendarAttr where Status=%s';
		$result = $this->query($sql,array(\haibao\cms\model\data\CalendarAttr::STATUS_ENABLE));
		if($result){
			while($result->fetch_assoc()){
				$tag = $result->getData('Id');
				$attrArr[$tag]['ParentId'] = $result->getData('ParentId');
				$attrArr[$tag]['Name'] = $result->getData('Name');
			}
			foreach($attrArr as $key=>$item){
				if($item['ParentId'] > 0){
					$rootAttr = $attrArr[$item['ParentId']]['Name'];
					$resArr[$rootAttr][$key] = $item['Name'];
				}
			}
		}
		return $resArr;
	}

	public function getAttrListByAttrId($id , $page = 1){
		$limit = ($page-1)*15;
		$whereAttrId = $id ? ' WHERE CR.CalendarAttrId = %s ' : ' group by CI.ArticleId ';
		$sql = 'select a.Id,a.Title,a.PublishId,b.CalendarId FROM `Article` a
				INNER JOIN (
					SELECT CI.ArticleId,CI.Id as CalendarId
					FROM CalendarIndex CI LEFT JOIN CalendarRelAttr CR
					ON CI.Id = CR.CalendarId
					'.$whereAttrId.' ) b
				ON a.Id = b.ArticleId WHERE a.Published = %s AND a.Status = %s and a.Level >  0
				ORDER BY a.PublishTime DESC limit %s,15';
		if($id){
			$result = $this->query($sql,array($id,\haibao\cms\model\data\Article::PUBLISHED_YES,\haibao\cms\model\data\Article::STATUS_ENABLE,$limit));

		}else{
			$result = $this->query($sql,array(\haibao\cms\model\data\Article::PUBLISHED_YES,\haibao\cms\model\data\Article::STATUS_ENABLE,$limit));
		}

		$calendar = $calendarIds = array();
		if($result){
			while($result->fetch_assoc()){
				$calendarIds[] = $result->getData('CalendarId');
				$tag = $result->getData('Id');
				$calendar[$tag]['Title'] = $result->getData('Title');
				$calendar[$tag]['PublishId'] = $result->getData('PublishId');
				$calendar[$tag]['Calendar'] = $result->getData('CalendarId');
			}
			$calendarAttrs = $this->getLastAttrByCalendarIds($calendarIds);
			foreach($calendar as $key=>$item){
				$calendar[$key]['Attr'] = $calendarAttrs[$item['Calendar']];
			}
		}
		return $calendar;
	}
	public function getResultCountForCalendarList($attrId = 0){
		$whereAttrId = $attrId ? ' WHERE CR.CalendarAttrId = %s ' : ' group by CI.ArticleId ';
		$sql = /** @lang text */
			'select count(*) as count FROM `Article` a
				INNER JOIN (
					SELECT CI.ArticleId,CI.Id as CalendarId
					FROM CalendarIndex CI LEFT JOIN CalendarRelAttr CR
					ON CI.Id = CR.CalendarId
					'.$whereAttrId.' ) b
				ON a.Id = b.ArticleId WHERE a.Published = %s AND a.Status = %s and a.Level >  0';
		if($attrId){
			$result = $this->query($sql,array($attrId,\haibao\cms\model\data\Article::PUBLISHED_YES,\haibao\cms\model\data\Article::STATUS_ENABLE));

		}else{
			$result = $this->query($sql,array(\haibao\cms\model\data\Article::PUBLISHED_YES,\haibao\cms\model\data\Article::STATUS_ENABLE));
		}
		$count = $result->fetch_assoc();
		return isset($count['count']) ? $count['count'] : 0;
	}

	private function getLastAttrByCalendarIds($calendarIds){
		$str = implode(',',$calendarIds);
		$str = preg_replace('/(\d+)/','%s',$str);
		$sql = 'select * from (
					SELECT Id,CalendarId,CalendarAttrId
					FROM CalendarRelAttr
					WHERE CalendarId IN('.$str.')
					order by Id desc) as A group by A.CalendarId';
		$result = $this->query($sql,$calendarIds);
		$resArr = array();
		if($result){
			while($result->fetch_assoc()){
				$resArr[$result->getData('CalendarId')] = $result->getData('CalendarAttrId');
			}
		}
		return $resArr;

	}


	public function getHaibao(){
		$sql = 'select Id,RealName,LeaderId,Permission from User where Status = 1';
		$result = $this->query($sql);
		$haibao = array();
		while($result->fetch_assoc()){
			$tag = $result->getData('Id');
			$haibao[$tag]['UserId'] = $result->getData('Id');
			$haibao[$tag]['Name'] = $result->getData('RealName');
			$haibao[$tag]['LeaderId'] = $result->getData('LeaderId');
			$haibao[$tag]['Permission'] = $result->getData('Permission');
		}
		return $haibao;
	}

	public function getCalendarsInDate($year,$month){
		$resArr = array();
		$startDate = $year.'-'.$month.'-01';
		$endDate = $year.'-'.$month.'-31';
		$sql = 'SELECT
			 a.Id as ArticleId,
			 a.ShortTitle,
			 a.PublishId,
			 a.PublishTime
			FROM
			 Article AS a
			INNER JOIN CalendarIndex AS b ON a.Id = b.ArticleId
			   WHERE
			a.Status = %s
			AND a.Published = %s
			AND a.PublishTime BETWEEN %s and %s
			ORDER BY
			 a.PublishTime DESC';
		$result = $this->query($sql,array(\haibao\cms\model\data\Article::STATUS_ENABLE,\haibao\cms\model\data\Article::PUBLISHED_YES,$startDate,$endDate));
		if($result){
			while($result->fetch_assoc()){
				$tmpArr = array();
				$tmpArr['ArticleId'] = $result->getData('ArticleId');
				$tmpArr['Title'] = $result->getData('ShortTitle');
				$tmpArr['PublishId'] = $result->getData('PublishId');
				$tmpArr['PublishTime'] = $result->getData('PublishTime');
				$resArr[] = $tmpArr;
			}
		}
		return $resArr;
	}

	public function checkLikeByCalendarIds($uid,$ids){
		$resArr = array();
		$str = preg_replace('/(\d+)/','%s',$ids);
		$likeSql = 'select CalendarId from CalendarLike WHERE UserId = %s and CalendarId in ('.$str.')';
		$likeIds = $this->query($likeSql,array_merge_recursive(array($uid),explode(',',$ids)));
		$likeCalendarIds = array();
		if($likeIds) {
			while ($likeIds->fetch_assoc()) {
				$likeCalendarIds[] = $likeIds->getData('CalendarId');
			}
			if($likeCalendarIds){
				$str = implode(',', $likeCalendarIds);
				$str = preg_replace('/(\d+)/', '%s', $str);
				$sql = 'SELECT CalendarId,count(*) AS LikeCount FROM CalendarLike WHERE CalendarId IN (' . $str . ') GROUP BY CalendarId';
				$hasCalendar = $this->query($sql, $likeCalendarIds);
				if ($hasCalendar) {
					while ($hasCalendar->fetch_assoc()) {
						$resArr[$hasCalendar->getData('CalendarId')] = $hasCalendar->getData('LikeCount');
					}
				}
			}
		}
			return $resArr;
	}

	public function addLike($uid,$id){
		$sql = 'insert into CalendarLike (CalendarId,UserId,CreateTime) values (%s,%s,%s)';
		$time = new \DateTime();
		$this->query($sql,array($id,$uid,$time));

		$countSql = 'select count(*) as Count from CalendarLike WHERE CalendarId = %s';
		$count = $this->query($countSql,array($id))->fetch_assoc();
		return $count['Count'];

	}

	public function getAttrsByArticleIds($articleIds){
		$str = preg_replace('/(\d+)/','%s',implode(',',$articleIds));
		$sql = 'select Id,ArticleId from CalendarIndex where ArticleId in ('.$str.')';
		$result = $this->query($sql,$articleIds);
		$calendarIds = $attrs = array();
		if($result){
			while($result->fetch_assoc()){
				$calendarIds[$result->getData('ArticleId')] = $result->getData('Id');
			}
		}
		$calendarAttrs  = $this->getLastAttrByCalendarIds($calendarIds);
		$resArr = array();
		foreach($calendarIds as $key=>$attr){
			$resArr[$key] = isset($calendarAttrs[$attr]) ? $calendarAttrs[$attr] : 0;
		}
		return $resArr;
	}

	public function getCalendarAttsByCalendarId($calendarId){
		$sql = 'select CalendarAttrId from CalendarRelAttr WHERE CalendarId = %s';
		$result = $this->query($sql,array($calendarId));
		$resArr = array();
		if($result){
			while($result->fetch_assoc()){
				$resArr[] = $result->getData('CalendarAttrId');
			}
		}
		return $resArr;
	}
}
